package com.tsj.spzx.pay.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.tsj.spzx.exception.TsjException;
import com.tsj.spzx.model.entity.pay.PaymentInfo;
import com.tsj.spzx.model.vo.common.ResultCodeEnum;
import com.tsj.spzx.pay.Properties.AlipayProperties;
import com.tsj.spzx.pay.service.AlipayService;
import com.tsj.spzx.pay.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedHashMap;
import java.util.Map;


@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private AlipayProperties alipayProperties;

    /**
     * 确认支付
     * 点击确认支付后，调用支付宝接口，会给我们返回一个页面，这个页面就是支付宝的支付页面
     * @param orderNo 订单编号
     * @return
     */
    @Transactional
    @Override
    public String submitAlipay(String orderNo) {
        // 现根据订单编号orderNo 保存支付记录
        // 添加成功后也需要返回对象，目的就是在下面封装支付宝的支付页面所需要的参数
        PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(orderNo);

        // 创建对应的request
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        // 同步回调： 支付成功后，支付宝会自动跳转到该URL（通常是一个前端页面）
        alipayRequest.setReturnUrl(alipayProperties.getReturnPaymentUrl());
        // 异步回调 支付宝会主动发送POST请求到该URL（后端API）携带的有具体参数 我们需要返回“success”
        alipayRequest.setNotifyUrl(alipayProperties.getNotifyPaymentUrl());

        // 准备请求参数
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("out_trade_no", paymentInfo.getOrderNo());
        map.put("product_code", "QUICK_WAP_WAY");
        map.put("total_amount", paymentInfo.getAmount());
        map.put("subject", paymentInfo.getContent());
        alipayRequest.setBizContent(JSON.toJSONString(map));

        // 调用支付宝服务接口 发送请求
        try {
            AlipayTradeWapPayResponse response = alipayClient.pageExecute(alipayRequest);
            if (response.isSuccess()){
                String form = response.getBody();
                return form;  // 就是form表单页面
            }else {
                throw new TsjException(ResultCodeEnum.DATA_ERROR);
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
